
#include <stdio.h>          // 标准输入输出
#include <stdint.h>         // 几种扩展的整数类型和宏
#include <stdlib.h>         // 标准函数库
#include <string.h>         // 字符串处理(操作字符数组)
#include "ohos_init.h"          // 用于初始化服务(services)和功能(features)
#include "cmsis_os2.h"          // CMSIS-RTOS API V2

#include "common.h"
#include "wifi_connecter.h"     // easy wifi (station模式)
#include "bmsinfo.h"


/**
 * @brief
 *
 * @param buff
 * @param size
 */
void Debug_DataBuff(const uint8_t* head, const uint8_t* buff, uint16_t size)
{
//    DebugMsg("\r ------------- data --------------- \n");
//    DebugMsg("\r Debug buffer len = %d \r\n", size);

	DebugMsg("\r%s[len = %d] :", head, size);
    for (uint32_t i = 0; i < size; i++)
    {
        DebugMsg(" %02x", buff[i]);
    }
    DebugMsg("\r\n");
}


/**
 * @brief 
 * 
 */
void initOled(void)
{
    OledInit();
    OledFillScreen(0);
    IoTI2cInit(AHT20_I2C_IDX, AHT20_BAUDRATE); 
}

/**
 * @brief 
 * 
 */
void connectWifi(void)
{
    // 连接到热点
    if (ConnectToHotspot(PARAM_HOTSPOT_SSID, PARAM_HOTSPOT_PSK) != 0)
    {
        // 连接到热点失败
        osal_printk("[long] Connect to AP failed\n"); // 输出错误信息
        return;
    }
}
/**
 * @brief 
 * 
 */
void waitIpaddrStatus(void)
{
    osal_printk("[long] check Ip address ... \n");
    // OledShowString(10, 0, "Env ...", 1);
    _IPAddrPkgs_* p_Ipaddr = get_WifiIPaddress();

    while (p_Ipaddr->flag_ipAddrst == 0)
    {
        osDelay(10); 
    }
    
    {
        uint32_t ip_addr = p_Ipaddr->ip_addr;
    #if CFG_EN_OLED_DISP
        char strline[32];
        sprintf(strline, "%d.%d.%d.%d", ip_addr & 0xFF, ((ip_addr >> 8) & 0xFF), ((ip_addr >> 16) & 0xFF), ((ip_addr >> 24) & 0xFF));
        OledShowString(0, 0, strline, 1); 
    #endif

    }
}



/**
 * @brief 
 * 
 */
void readAht20TempHumiValue(void)
{
    float temperature = 0.0f;                           // 温度
    float humidity = 0.0f;                              // 湿度
    _SystemDataStru *bmsInf = getBmsInf();

    // char templine[32] = {0};
    // char humiline[32] = {0};
    char strline[32] = {0};

    if (GetTempHumiLevel(&temperature, &humidity) == 0) //成功获取数字温湿度传感器数据
    {   
        bmsInf->env_humidity = humidity;
        bmsInf->env_temperature = temperature;

    #if CFG_EN_OLED_DISP
        // snprintf(templine, sizeof(templine), "temp: %.2f", temperature);
        // snprintf(humiline, sizeof(humiline), "humi: %.2f", humidity);

        // OledShowString(10, 2, templine, 1);
        // OledShowString(10, 4, humiline, 1);

        snprintf(strline, sizeof(strline), "T:%.2f H:%.2f", temperature, humidity);
        OledShowString(2, 2, strline, 1);
    #endif
    }
}


/**
 * @brief 
 * 
 */
void SystemCntTickHandler(void)
{
    static uint32_t cnt_tick_timer = 0;

#if CFG_EN_OLED_DISP

    // char strline[16];
    // sprintf(strline, "Tick: %03d", cnt_tick_timer);
    // OledShowString(2, 7, strline, 1); 
    
    cnt_tick_timer ++;
    cnt_tick_timer =  cnt_tick_timer % 1000;
#endif
}

